package tasks.io.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;

/**
 * @author tanyaowu
 * 2017年10月19日 上午9:41:00
 */
public class ByteBufferUtils {
    @SuppressWarnings("unused")
    private static final Logger log = LoggerFactory.getLogger(ByteBufferUtils.class);

    /**
     * 组合两个bytebuffer，把可读部分的组合成一个新的bytebuffer
     */
    public static ByteBuffer composite(ByteBuffer byteBuffer1, ByteBuffer byteBuffer2) {
        int capacity = byteBuffer1.remaining() + byteBuffer2.remaining();
        ByteBuffer byteBuffer = ByteBuffer.allocate(capacity);

        byteBuffer.put(byteBuffer1);
        byteBuffer.put(byteBuffer2);

        byteBuffer.position(0);
        byteBuffer.limit(byteBuffer.capacity());
        return byteBuffer;
    }


    /**
     * @param src 本方法不会改变position等指针变量
     * @return
     * @author tanyaowu
     */
    public static ByteBuffer copy(ByteBuffer src) {
        int startindex = src.position();
        int endindex = src.limit();
        return copy(src, startindex, endindex);
    }

    /**
     * @param src        本方法不会改变position等指针变量
     * @param startindex 从0开始
     * @param endindex
     */
    public static ByteBuffer copy(ByteBuffer src, int startindex, int endindex) {

        int initPosition = src.position();
        int initLimit = src.limit();
        src.position(startindex);
        src.limit(endindex);
        //
        int size = endindex - startindex;
        ByteBuffer byteBuffer = ByteBuffer.allocate(size);
        byteBuffer.put(src);
        byteBuffer.flip();

        src.position(initPosition);
        src.limit(initLimit);
        return byteBuffer;
    }

}
